﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using jaysJourney_v01.Utils;
using jaysJourney_v01.Common;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace jaysJourney_v01.States
{
    class RegisterState : State
    {
        /**
         * MEMBER VARIABLES
         * */

        // Common
        private SpriteBatch mainSpriteBatch;
        private InputGroup menuButtonGroup;

        private Texture2D interfaceBG;
        private bool loading;
        private Texture2D loadingscreen;

        // Buttons
        private InputField username;
        private InputField email;
        private InputField password;
        private InputField passwordRepeat;
        private Button register;
        private Button back;
        private Button exit;

        /**
         * METHODS
         * */

        public RegisterState(String name, StateManager stateManager) : base(name, stateManager) { }

        public override void initialize()
        {
            mainSpriteBatch = this.parentSpriteBatch;

            this.interfaceBG = this.getGame().Content.Load<Texture2D>(@"Textures\Interface\main_menu_v5");
            this.loadingscreen = this.getGame().Content.Load<Texture2D>(@"Textures\Preloader\loadingscreen");


            // Buttons
            this.username = new InputField(this, "Enter Username", new Vector2(this.getGame().GraphicsDevice.Viewport.Width / 2 - 150, 350), @"Textures\Textfield\stxtField", @"Textures\Textfield\stxtFieldHover", @"Textures\Textfield\stxtFieldAc", 20, true, false, false);
            this.email = new InputField(this, "Enter E-Mail", new Vector2(this.getGame().GraphicsDevice.Viewport.Width / 2 - 150, 400), @"Textures\Textfield\stxtField", @"Textures\Textfield\stxtFieldHover", @"Textures\Textfield\stxtFieldAc", 20, false, false, true);
            this.password = new InputField(this, "Enter Password", new Vector2(this.getGame().GraphicsDevice.Viewport.Width / 2 - 150, 450), @"Textures\Textfield\stxtField", @"Textures\Textfield\stxtFieldHover", @"Textures\Textfield\stxtFieldAc", 20, false, true, false);
            this.passwordRepeat = new InputField(this, "Repeat Password", new Vector2(this.getGame().GraphicsDevice.Viewport.Width / 2 - 150, 500), @"Textures\Textfield\stxtField", @"Textures\Textfield\stxtFieldHover", @"Textures\Textfield\stxtFieldAc", 20, false, true, false);
            this.register = new Button(this, "REGISTER", @"Textures\Interface\menu_button", @"Textures\Interface\menu_button_ac", 580, Color.White, true, true);
            this.back = new Button(this, "BACK", @"Textures\Interface\back_btn", @"Textures\Interface\back_btn_ac", 94, this.getGame().GraphicsDevice.Viewport.Height - 74, Color.White, false, false);
            this.exit = new Button(this, "EXIT", @"Textures\Interface\quit_btn", @"Textures\Interface\quit_btn_ac", 20, this.getGame().GraphicsDevice.Viewport.Height - 74, Color.White, false, false);


            this.menuButtonGroup = new InputGroup(this, this.mainSpriteBatch);
            this.menuButtonGroup.addButton(username);
            this.menuButtonGroup.addButton(email);
            this.menuButtonGroup.addButton(password);
            this.menuButtonGroup.addButton(passwordRepeat);
            this.menuButtonGroup.addButton(register);
            this.menuButtonGroup.addButton(back);
            this.menuButtonGroup.addButton(exit);
        }

        public override void update(GameTime gameTime)
        {
            // set mouse invis
            if (loading)
            {
                loading = false;
                // check if user exists
                if (WebLoader.doesUserExist(this.menuButtonGroup.getContent("Enter Username")) == 1)
                {
                    // Error User Exists
                    this.getGame().pushMessage("Sorry, " + this.menuButtonGroup.getContent("Enter Username") + " already exists!", true);
                    this.menuButtonGroup.resetInputField();
                }
                else if (WebLoader.doesUserExist(this.menuButtonGroup.getContent("Enter Username")) == 0)
                {
                    String success = WebSaver.saveUser(this.menuButtonGroup.getContent("Enter Username"), this.menuButtonGroup.getContent("Enter Password"), this.menuButtonGroup.getContent("Enter E-Mail"), CONST.USER_STARTMONEY, CONST.USER_STARTXP);
                    if (success != "version")
                    {
                        this.menuButtonGroup.resetInputField();
                        this.getStateManager().setActiveState("loginState");
                        this.getGame().pushMessage("Gratz, " + this.menuButtonGroup.getContent("Enter Username") + " successfully created!", false);
                    }
                    else
                    {
                        // old version
                        this.getGame().pushMessage("Your version is too old, please get the latest version!", true);
                    }
                }
                else
                {
                    // Error Database
                    this.getGame().pushMessage("Could not connect to database!", true);
                    this.menuButtonGroup.resetInputField();
                }
            }


            // update buttons

            Button click = this.menuButtonGroup.update(gameTime);

            // handle button clicks

            if (click != null && click.getName() == "EXIT") this.getGame().Exit();
            if (click != null && click.getName() == "BACK") this.getStateManager().setActiveState("loginState");
            else if (click != null && click.getName() == "REGISTER")
            {
                // check if everything is filled out
                if (this.menuButtonGroup.getContent("Enter Username") != "" && this.menuButtonGroup.getContent("Enter Username") != "Enter Username" && this.menuButtonGroup.getContent("Enter E-Mail") != "" && this.menuButtonGroup.getContent("Enter Password") != "" && this.menuButtonGroup.getContent("Repeat Password") != "")
                {
                    // check if pw and pwreapat match
                    if (this.menuButtonGroup.getContent("Enter Password") == this.menuButtonGroup.getContent("Repeat Password"))
                    {
                        // check if email is really an email
                        if (checkEmail(this.menuButtonGroup.getContent("Enter E-Mail")))
                        {
                            loading = true;
                           
                        }
                        else
                        {
                            // No valid email
                            this.getGame().pushMessage("Please insert a valid email", true);
                        }
                    }
                    else
                    {
                        // PW and PWRepeat does not match
                        this.getGame().pushMessage("Passwords dont match!", true);
                    }
                }
                else
                {
                    // Error Empty Fields
                    this.getGame().pushMessage("Please fill out all fields!", true);
                }
            }
        }

        // MAIN DRAW

        public override void draw(GameTime gameTime)
        {
            // draw bg
            this.mainSpriteBatch.Draw(this.getGame().menuBg, new Rectangle(0, 0, this.getGame().GraphicsDevice.Viewport.Width, this.getGame().GraphicsDevice.Viewport.Height), new Rectangle(0, 0, this.getGame().menuBg.Width, this.getGame().menuBg.Height), Color.White);

            // draw interface bg
            this.mainSpriteBatch.Draw(this.interfaceBG, new Rectangle((this.getGame().GraphicsDevice.Viewport.Width / 2) - this.interfaceBG.Width / 2, 0, this.interfaceBG.Width, this.interfaceBG.Height), new Rectangle(0, 0, this.interfaceBG.Width, this.interfaceBG.Height), Color.White);

            // draw buttons
            this.menuButtonGroup.draw(gameTime);
            if (loading) this.mainSpriteBatch.Draw(this.loadingscreen, new Rectangle((this.getGame().GraphicsDevice.Viewport.Width / 2) - this.loadingscreen.Width / 2, (this.getGame().GraphicsDevice.Viewport.Height / 2) - this.interfaceBG.Height / 2, this.loadingscreen.Width, this.loadingscreen.Height), new Rectangle(0, 0, this.loadingscreen.Width, this.loadingscreen.Height), Color.White);

        }

        public override void onEnterState()
        {
            this.username.setNewPosition(this.getGame().GraphicsDevice.Viewport.Width / 2 - 120, 350);
            this.email.setNewPosition(this.getGame().GraphicsDevice.Viewport.Width / 2 - 120, 400);
            this.password.setNewPosition(this.getGame().GraphicsDevice.Viewport.Width / 2 - 120, 450);
            this.passwordRepeat.setNewPosition(this.getGame().GraphicsDevice.Viewport.Width / 2 - 120, 500);
            this.register.setNewPosition(580);
            this.back.setNewPosition(94, this.getGame().GraphicsDevice.Viewport.Height - 74);
            this.exit.setNewPosition(20, this.getGame().GraphicsDevice.Viewport.Height - 74);
        }

        // check email

        private bool checkEmail(String email)
        {
            int amountAT = 0;
            int amountDot = 0;
            int posAT = 0;
            int lastDot = 0;

            for (int i = 0; i < email.Length; i++)
            {
                if (email[i] == '@') { amountAT++; posAT = i; }
                else if (email[i] == '.') { amountDot++; lastDot = i; }
            }

            if (amountAT == 1 && amountDot > 0 && amountDot <= 2 && posAT < lastDot) return true;
            return false;
        }
    }
}
